<?php

namespace think\admin\service;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Dysmsapi\Dysmsapi;
use think\admin\Exception;
use think\admin\model\SysSms;
use think\admin\Service;

/**
 * 阿里云短雠发送服务
 * @class AlibabaSmsService
 * @package think\admin\service
 */
class AlibabaSmsService extends Service
{
    /**
     * AccessKey ID
     * @var string
     */
    protected string $accessKeyId;

    /**
     * accessKey Secret
     * @var string
     */
    protected string $accessKeySecret;

    /**
     * Region Id
     * @var string
     */
    protected string $regionId;

    /**
     * Sign Name
     * @var string
     */
    protected string $signName;

    /**
     * 发送单个短信
     * @param string $phoneNumbers
     * @param string $signName
     * @param string $templateCode
     * @param string $templateParam json_encode(['code' => '111'])
     * @return bool
     */
    public function singleSendSms(string $phoneNumbers, string $signName = '', string $templateCode = '', string $templateParam = ''): bool
    {
        try {
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId($this->regionId)
                ->asDefaultClient();

            $result = Dysmsapi::v20170525()
                ->sendSms()
                ->withPhoneNumbers($phoneNumbers)
                ->withSignName($signName ?: $this->signName)
                ->withTemplateCode($templateCode)
                ->withTemplateParam($templateParam)
                ->connectTimeout(60)
                ->timeout(65)
                ->request();

            $state = false;
            $dat = [
                'engine' => 'ALIYUN',
                'phone_numbers' => $phoneNumbers,
                'sign_name' => $signName ?: $this->signName,
                'template_code' => $templateCode,
                'template_param' => $templateParam
            ];
            if ($result->toArray()) {
                $state = true;
                $dat['receipt_info'] = json_encode($result->toArray());
            }
            SysSms::mk()->insert($dat);
            return $state;
        } catch (ClientException|ServerException $e) {
            return false;
        }
    }

    /**
     * 控制器初始化
     * @return void
     * @throws Exception
     */
    protected function initialize()
    {
        $this->accessKeyId = sysconfig('SMS_ALIYUN', 'SQM_SMS_ALIYUN_ACCESS_KEY_ID');
        $this->accessKeySecret = sysconfig('SMS_ALIYUN', 'SQM_SMS_ALIYUN_ACCESS_KEY_SECRET');
        $this->regionId = sysconfig('SMS_ALIYUN', 'SQM_SMS_ALIYUN_REGION_ID');
        $this->signName = sysconfig('SMS_ALIYUN', 'SQM_SMS_ALIYUN_DEFAULT_SIGN_NAME');
    }
}
